package device

import (
	"backend/internal/common/errorx"
	modbusTypes "backend/internal/core/types"
	"backend/internal/db/model"
	"backend/internal/svc"
	"backend/internal/types"
	"context"
	"fmt"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddDeviceLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddDeviceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddDeviceLogic {
	return &AddDeviceLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddDeviceLogic) AddDevice(req *types.CreateDeviceReq) (resp *types.CreateDeviceResp, err error) {
	// 构造 GORM 模型
	device := model.Device{
		Name:     req.DeviceName,
		IP:       req.IP,
		Port:     int32(req.Port),
		Protocol: req.Protocol,
	}

	// 新建 modbus客户端
	switch req.Protocol {
	case modbusTypes.Tcp:
		l.svcCtx.ClientManager.AddModbusTCPClient(req.DeviceName, req.IP, req.Port)
	case modbusTypes.RtuOverTcp:
		l.svcCtx.ClientManager.AddModbusRtuOverTcpClient(req.DeviceName, req.IP, req.Port)
	case modbusTypes.Rtu:
		break
	default:
		return nil, errorx.NewCodeError(http.StatusBadRequest, fmt.Sprintf("不支持的协议: %v", req.Protocol))
	}

	// 插入数据库
	result := l.svcCtx.GormDB.Create(&device)
	if result.Error != nil {
		errorStr := fmt.Sprintf("添加设备失败: %v", result.Error)
		logx.Errorf(errorStr)
		return nil, errorx.NewCodeError(http.StatusBadRequest, fmt.Sprintf("添加设备失败: %v", result.Error))
	}

	// 返回成功响应
	return &types.CreateDeviceResp{
		Status: http.StatusOK,
		Msg:    fmt.Sprintf("添加设备成功: %v", device.Name),
		Data:   true,
	}, nil
}
